﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using System.Reflection;
using PluginAPI;

namespace PluginManage
{
    /// <summary>
    /// 插件管理器
    /// </summary>
    public class PluginManage: IPluginService
    {
        /// <summary>
        /// 宿主
        /// </summary>
        private IApplication _app;

        /// <summary>
        /// 插件集合
        /// </summary>
        public Dictionary<string, IPlugin> plugs;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="app">宿主程序对象</param>
        public PluginManage(IApplication app)
        {
            _app = app;
            plugs = new Dictionary<string, IPlugin>(); 
        }

        /// <summary>
        /// 加载全部插件
        /// </summary>
        public void LoadAllPlugin()
        {
            //1.获取插件存放目录
            string dirPlug = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugin");
            if (!Directory.Exists(dirPlug)) return;

            //2.获取插件目录下所有插件
            DirectoryInfo dirInfo = new DirectoryInfo(dirPlug);
            FileInfo[] dlls = dirInfo.GetFiles("*.dll");

            //3.循环加载插件
            foreach (FileInfo file in dlls)
            {
                Assembly assembly = Assembly.LoadFile(file.FullName);
                try
                {
                    Type[] types = assembly.GetTypes();
                    foreach (Type type in types)
                    {
                        if (type.GetInterface("IPlugin") != null)
                        {
                            IPlugin instance = (IPlugin)Activator.CreateInstance(type);

                            instance.application = _app;
                            plugs.Add(file.Name, instance);
                            //instance.Load();
                        }
                    }
                }
                catch { }
            }
        }
    }
}